package no.zappi;

import java.awt.Container;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import com.sun.image.codec.jpeg.*;

public class ImageViewer {

	private int tumbHeight = 50;
	private int tumbWidth = 50;
	private double tumbRatio = (double) tumbWidth / (double) tumbHeight;
	
	public ImageViewer() throws Exception {
		String folderName = "c:/";
		List<Image> imageListe = getImagesFromFolder(folderName);
		MediaTracker mediaTracker = new MediaTracker(new Container());
		int mediaTrackerId = 0;
		for (Image image : imageListe) {
			mediaTracker.addImage(image, mediaTrackerId);
			mediaTracker.waitForID(mediaTrackerId);
			mediaTrackerId++;
			
			int imageHeight = image.getHeight(null);
			int imageWidth = image.getWidth(null);
			double imageRatio = (double) imageWidth / (double) imageHeight;
			
			if (tumbRatio < imageRatio) {
				tumbHeight = (int) (tumbWidth / imageRatio);
			} else {
				tumbWidth = (int) (tumbHeight * imageRatio);
			}
			
			BufferedImage tumbImage = new BufferedImage(tumbWidth, tumbHeight, BufferedImage.TYPE_INT_RGB);
			Graphics2D graphics2d = tumbImage.createGraphics();
			graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
			graphics2d.drawImage(image, 0, 0, tumbWidth, tumbHeight, null);
			
			BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("c:/test" + mediaTrackerId + ".jpg"));
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(tumbImage);
			int quality = Integer.parseInt("40");
			quality = Math.max(0, Math.min(quality, 100));
			param.setQuality((float)quality / 100.f, false);
			encoder.setJPEGEncodeParam(param);
			encoder.encode(tumbImage);
			out.close();
			
		}
	}
	
	public static void main(String[] args) throws Exception {
		
		ImageViewer imageViewer = new ImageViewer();
		System.out.println("Done. ");
		System.exit(0);
	}
	
	private List<Image> getImagesFromFolder(String folderName) {
		List<Image> imageList = new ArrayList<Image>();
		File directory = new File(folderName);
		
		//filter to only return files and not directories.
		FileFilter fileFilter = new FileFilter() {
			
			@Override
			public boolean accept(File file) {
				return file.isFile();
			}
		};
		
		File[] files = directory.listFiles(fileFilter);
		for (int i = 0; i < files.length; i++) {
			imageList.add(Toolkit.getDefaultToolkit().createImage(files[i].getName()));
		}
		
		return imageList;
	}
 }
